Object Oriented Programming

Input/Output Statements, Command Line Arguments,
Data Types, Variables & Operators

Unit I - Lectures 4 & 5

BTech 4th Semester

UPES - University of Petroleum and Energy Studies

Instructor: Mohsin Dar

Input/Output Statements in Java

Output Statements

Java provides several methods to display output to the console:

1. System.out.print()

Prints text without adding a new line at the end.

                    System.out.print("Hello ");
                    System.out.print("World");
                    // Output: Hello World
                

2. System.out.println()

Prints text and moves cursor to the next line.

                    System.out.println("Hello");
                    System.out.println("World");
                    // Output: 
                    // Hello
                    // World
                

Input Statements in Java

Using Scanner Class

The Scanner class is used to get user input from various sources.

import java.util.Scanner; public class InputExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.println("Hello " + name); System.out.println("You are " + age + " years old"); sc.close(); } }

Scanner Class Methods

Method Description Return Type
nextInt() Reads an integer value int
nextDouble() Reads a double value double
nextFloat() Reads a float value float
next() Reads a single word (till space) String
nextLine() Reads a complete line String
nextBoolean() Reads a boolean value boolean

Command Line Arguments

Command line arguments allow you to pass information to a program when it starts executing.

What are Command Line Arguments?

Arguments passed to the program at runtime through the command line interface.

Syntax

public class CommandLineExample { public static void main(String[] args) { System.out.println("Number of arguments: " + args.length); for(int i = 0; i < args.length; i++) { System.out.println("Argument " + i + ": " + args[i]); } } }

Execution

java CommandLineExample Hello World 123

Command Line Arguments - Example

public class Calculator { public static void main(String[] args) { if(args.length < 2) { System.out.println("Please provide two numbers"); return; } int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); int sum = num1 + num2; System.out.println("Sum: " + sum); } } // Execution: java Calculator 10 20 // Output: Sum: 30
Note: All command line arguments are received as Strings. You need to convert them to appropriate data types using wrapper classes like Integer.parseInt(), Double.parseDouble(), etc.

Data Types in Java

Java is a strongly typed language. Every variable must have a data type.

Two Categories of Data Types:

1. Primitive Data Types

Basic data types built into the Java language (8 types)

2. Non-Primitive Data Types

Reference types like Classes, Interfaces, Arrays, Strings

Key Difference: Primitive types store actual values, while non-primitive types store references (memory addresses) to objects.

Primitive Data Types

Data Type Size Range Default Value
byte 1 byte -128 to 127 0
short 2 bytes -32,768 to 32,767 0
int 4 bytes -2³¹ to 2³¹-1 0
long 8 bytes -2⁶³ to 2⁶³-1 0L
float 4 bytes ±3.4e-038 to ±3.4e+038 0.0f
double 8 bytes ±1.7e-308 to ±1.7e+308 0.0d
char 2 bytes 0 to 65,535 (Unicode) '\u0000'
boolean 1 bit true or false false

Data Types - Examples

public class DataTypesDemo { public static void main(String[] args) { // Integer types byte age = 25; short year = 2024; int population = 1400000000; long distance = 9876543210L; // L suffix for long // Floating-point types float price = 99.99f; // f suffix for float double pi = 3.14159265359; // Character type char grade = 'A'; char symbol = '\u0041'; // Unicode for 'A' // Boolean type boolean isPassed = true; boolean isRaining = false; System.out.println("Age: " + age); System.out.println("Grade: " + grade); System.out.println("Passed: " + isPassed); } }

Variables in Java

A variable is a named memory location that stores a value.

Variable Declaration Syntax:

                    dataType variableName;
                    dataType variableName = value;
                

Types of Variables:

1. Local Variables

Declared inside methods, constructors, or blocks. Must be initialized before use.

2. Instance Variables

Declared inside a class but outside methods. Each object has its own copy.

3. Static Variables (Class Variables)

Declared with static keyword. Shared among all instances of a class.

Variables - Example

                    public class VariablesDemo {
                        // Instance variable
                        int instanceVar = 10;
                        
                        // Static variable
                        static int staticVar = 20;
                        
                        public void display() {
                            // Local variable
                            int localVar = 30;
                            
                            System.out.println("Instance Variable: " + instanceVar);
                            System.out.println("Static Variable: " + staticVar);
                            System.out.println("Local Variable: " + localVar);
                        }
                        
                        public static void main(String[] args) {
                            VariablesDemo obj1 = new VariablesDemo();
                            VariablesDemo obj2 = new VariablesDemo();
                            
                            obj1.instanceVar = 100;  // Only obj1's copy changes
                            staticVar = 200;         // Shared by all objects
                            
                            obj1.display();
                            obj2.display();
                        }
                    }
                

Variable Naming Rules

Rules (Must Follow):

Conventions (Best Practices):

                        // Valid variable names
                        int age;
                        int student_age;
                        int $price;
                        int _count;

                        // Invalid variable names
                        int 2students;  // Cannot start with digit
                        int student-age; // Cannot use hyphen
                        int class;      // Cannot use keyword
                

Operators in Java

Operators are special symbols that perform specific operations on operands.

Types of Operators:

  1. Arithmetic Operators - Perform mathematical operations
  2. Relational Operators - Compare two values
  3. Logical Operators - Combine conditional statements
  4. Assignment Operators - Assign values to variables
  5. Unary Operators - Work with single operand
  6. Bitwise Operators - Perform bit-level operations
  7. Ternary Operator - Conditional operator

Arithmetic Operators

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 10 / 3 3 (integer division)
% Modulus (Remainder) 10 % 3 1
int a = 10, b = 3; System.out.println("Addition: " + (a + b)); // 13 System.out.println("Subtraction: " + (a - b)); // 7 System.out.println("Multiplication: " + (a * b)); // 30 System.out.println("Division: " + (a / b)); // 3 System.out.println("Modulus: " + (a % b)); // 1

Relational Operators

Used to compare two values. Returns boolean result (true or false).

Operator Name Example Result
== Equal to 5 == 3 false
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 5 <= 3 false

Logical Operators

Used to combine multiple conditions.

Operator Name Description Example
&& Logical AND Returns true if both conditions are true (5 > 3) && (8 > 5) → true
|| Logical OR Returns true if at least one condition is true (5 > 3) || (8 < 5) → true
! Logical NOT Reverses the boolean value !(5 > 3) → false
int age = 20; boolean hasLicense = true; // AND operator if(age >= 18 && hasLicense) { System.out.println("You can drive"); } // OR operator if(age < 18 || !hasLicense) { System.out.println("You cannot drive"); }

Assignment Operators

Operator Example Equivalent to
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
int num = 10; num += 5; // num = 15 num -= 3; // num = 12 num *= 2; // num = 24 num /= 4; // num = 6 num %= 4; // num = 2 System.out.println("Final value: " + num); // 2

Unary Operators

Operators that work with a single operand.

Operator Name Description
++ Increment Increases value by 1
-- Decrement Decreases value by 1
+ Unary plus Indicates positive value
- Unary minus Negates an expression
! Logical NOT Inverts boolean value

Pre-increment vs Post-increment:

int a = 5; int b = ++a; // Pre-increment: a becomes 6, then b = 6 System.out.println("a: " + a + ", b: " + b); // a: 6, b: 6 int c = 5; int d = c++; // Post-increment: d = 5, then c becomes 6 System.out.println("c: " + c + ", d: " + d); // c: 6, d: 5

Ternary Operator

A shorthand way to write if-else statements. Also called the conditional operator.

Syntax:

                    variable = (condition) ? expressionTrue : expressionFalse;
                

Example:

                    int age = 20;
                            String result = (age >= 18) ? "Adult" : "Minor";
                            System.out.println(result);  // Output: Adult

                            // Traditional if-else equivalent:
                            String result2;
                            if(age >= 18) {
                                result2 = "Adult";
                            } else {
                                result2 = "Minor";
                            }

                            // Finding maximum of two numbers
                            int a = 10, b = 20;
                            int max = (a > b) ? a : b;
                            System.out.println("Maximum: " + max);  // 20
                

Operator Precedence

Determines the order in which operators are evaluated in an expression.

Precedence Operator Description
1 (Highest) ++, -- Postfix increment/decrement
2 ++, --, +, -, ! Unary operators
3 *, /, % Multiplicative
4 +, - Additive
5 <, <=, >, >= Relational
6 ==, != Equality
7 && Logical AND
8 || Logical OR
9 ?: Ternary
10 (Lowest) =, +=, -=, *=, /=, %= Assignment

Operator Precedence - Example

                    int result;

                        // Example 1: Multiplication before addition
                        result = 5 + 3 * 2;
                        System.out.println(result);  // Output: 11 (not 16)
                        // Explanation: 3 * 2 = 6, then 5 + 6 = 11

                        // Example 2: Using parentheses to change precedence
                        result = (5 + 3) * 2;
                        System.out.println(result);  // Output: 16
                        // Explanation: 5 + 3 = 8, then 8 * 2 = 16

                        // Example 3: Complex expression
                        result = 10 + 5 * 2 - 3 / 3;
                        System.out.println(result);  // Output: 19
                        // Step 1: 5 * 2 = 10
                        // Step 2: 3 / 3 = 1
                        // Step 3: 10 + 10 - 1 = 19

                        // Example 4: Relational and logical operators
                        boolean flag = 5 > 3 && 10 < 20 || 8 == 8;
                        System.out.println(flag);  // Output: true
                
Best Practice: Use parentheses to make your intentions clear, even when not strictly necessary. This improves code readability.

Type Casting

Converting a value from one data type to another.

1. Widening (Implicit) Casting

Automatic conversion from smaller to larger data type. No data loss.

                    int num = 100;
                        long bigNum = num;      // int to long
                        float decimal = bigNum;  // long to float
                        double precise = decimal; // float to double

                        System.out.println(precise);  // 100.0
                                    

2. Narrowing (Explicit) Casting

Manual conversion from larger to smaller data type. May cause data loss.

double d = 99.99; int i = (int) d; // Explicit casting required System.out.println(i); // Output: 99 (decimal part lost) long l = 1000000L; int j = (int) l; System.out.println(j); // Output: 1000000

Comprehensive Example

                    import java.util.Scanner;

                    public class StudentGradeCalculator {
                        public static void main(String[] args) {
                            Scanner sc = new Scanner(System.in);
                            
                            // Input
                            System.out.print("Enter student name: ");
                            String name = sc.nextLine();
                            
                            System.out.print("Enter marks in Math: ");
                            int mathMarks = sc.nextInt();
                            
                            System.out.print("Enter marks in Science: ");
                            int scienceMarks = sc.nextInt();
                            
                            System.out.print("Enter marks in English: ");
                            int englishMarks = sc.nextInt();
                            
                            // Calculations
                            int total = mathMarks + scienceMarks + englishMarks;
                            double average = total / 3.0;
                            
                            // Grade determination using ternary operator
                            char grade = (average >= 90) ? 'A' :
                                        (average >= 80) ? 'B' :
                                        (average >= 70) ? 'C' :
                                        (average >= 60) ? 'D' : 'F';
                            
                            // Output
                            System.out.println("\n--- Student Report ---");
                            System.out.println("Name: " + name);
                            System.out.println("Total Marks: " + total + "/300");
                            System.out.println("Average: " + average + "%");
                            System.out.println("Grade: " + grade);
                            
                            sc.close();
                        }
                    }
                

Summary

Key Points Covered:

1. Input/Output Statements

2. Command Line Arguments

3. Data Types

4. Variables

5. Operators

Practice Questions

Question 1:

What will be the output of the following code?

                    int x = 10;
                    int y = x++ + ++x;
                    System.out.println("x: " + x + ", y: " + y);
                

Question 2:

Write a program that takes two numbers as command line arguments and displays their sum, difference, product, and quotient.

Question 3:

What is the difference between == and = operators?

Question 4:

Explain the difference between int division and double division with an example.

Question 5:

Create a program using Scanner class that takes student's marks in 5 subjects and calculates percentage and grade.

References & Next Lecture

Recommended Reading:

Next Lecture Topics:

Homework: Practice writing programs using all the operators covered today. Try solving at least 5 problems involving user input, calculations, and output.

Thank You!

Questions & Discussion

Instructor: Mohsin Dar

BTech 4th Semester - OOP using Java

UPES

1 / 27